package top.bigdata.service.impl;

import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import top.bigdata.constants.ZoneConstant;
import top.bigdata.mapper.TagMapper;
import top.bigdata.model.dto.MonthlyData;
import top.bigdata.model.dto.TagData;
import top.bigdata.service.api.ResultService;
import top.bigdata.service.api.TagIService;

import java.util.Comparator;
import java.util.List;

@Service
@RequiredArgsConstructor
public class TagServiceImpl implements TagIService {
    private final ResultService resultService;
    private final TagMapper tagMapper;

    /**
     * 获取最热标签
     */
    @Override
    public List<TagData> getHotTags(int tid) {
        var tids = ZoneConstant.tidToTids(tid);
        return resultService.cachedQueryList("hot_tag_" + tid, () ->
                tagMapper.getHotTags(tids), TagData.class);
    }

    /**
     * 获取标签各指标平均数的月度数据
     */
    @Override
    public List<MonthlyData> getDataMonthly(String tag) {
        var result = resultService.cachedQueryList("tag_avg_monthly_" + tag, () ->
                tagMapper.getDataMonthly(tag), MonthlyData.class);

        // 补充没有数据的月份
        var months = new String[]{"2024-09", "2024-10", "2024-11", "2024-12", "2025-01", "2025-02", "2025-03", "2025-04", "2025-05", "2025-06", "2025-07", "2025-08"};
        if (result.size() < months.length) {
            for (String month : months) {
                if (result.stream().noneMatch(res -> res.getMonth().equals(month))) { // 没有该月数据
                    result.add(new MonthlyData(month, 0, 0, 0, 0, 0, 0, 0));
                }
            }
        }
        // 排序
        result.sort(Comparator.comparing(MonthlyData::getMonth));
        return result;
    }
}
